var defineFormRules = function (rules) {
    var res = {};
    var defaultrule = {
        validate: {
            presence: true,
        },
        attr: {
            value: "",
        }
    };
    _.forEach(rules, function (rule, rulekey) {
        if (_.isObject(rule)) {
            res[rulekey] = Object.assign({}, _.cloneDeep(defaultrule), _.cloneDeep(rule));
        } else {
            res[rulekey] = _.cloneDeep(defaultrule);
        }
    });
    return res;
};

var getRandomArbitrary = function(min, max) {
  return Math.random() * (max - min) + min;
}

var randomStr = function(len) {
    var x = '0x1';
    for (var i = 0; i < len; i++) {
        x += '0';
    }
    return Math.floor((1 + Math.random()) * x)
        .toString(16)
        .substring(1);
};

var uniqueSelector = function(prefix, len = 6) {
    return prefix + randomStr(len);
};

var filterEmptyValue = function(obj) {
    var ret = {};
    _.forEach(obj, function (v, k) {
        if (isNumeric(v)) {
            ret[k] = v;
        }
        if (v) {
            ret[k] = v;
        }
    });
    return ret;
};

var filterObj = function(obj, filter) {
    var arr = filter;
    if (_.isString(filter))  {
        arr = [filter];
    }
    return _.pick(obj, Object.keys(obj).filter(function(v) {
        if (arr.indexOf(v) > -1) {
            return false;
        }
        return true;
    }));
};

var minute = function(m) {
    return m * 1000 * 60;
};

var getTodayDate = function() {
    var d = new Date();
    return new Date(d.getFullYear(), d.getMonth(), d.getDate());
};

var getDate = function(type, day) {
    var t = getTodayDate();
    if (type === "before") {
        return new Date(t.valueOf() - day * 3600 * 24 * 1000);
    } else if (type === "after") {
        return new Date(t.valueOf() + day * 3600 * 24 * 1000 );
    } else {
        return t;
    }
};

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

function getRandomArr(arr) {
    return arr[getRandomInt(0, arr.length - 1)];
}

var getValuefromDate = function (date) {
    var timezoneOffset = date.getTimezoneOffset();
    return date.valueOf() + timezoneOffset * 60 * 1000;
};

var isNumeric = function(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
};

export default {
    defineFormRules: defineFormRules,
    randomStr: randomStr,
    uniqueSelector: uniqueSelector,
    filterEmptyValue: filterEmptyValue,
    filterObj: filterObj,
    minute: minute,
    getTodayDate: getTodayDate,
    getDate: getDate,
    getValuefromDate: getValuefromDate,
    getRandomArbitrary: getRandomArbitrary,
    getRandomInt: getRandomInt,
    getRandomArr: getRandomArr,
    isNumeric: isNumeric
};